<template>
  <div class="app-container" style="overflow-x: hidden;">
    <br>
    <br>
    <el-form :model="query" ref="query" label-width="80px">
      <el-row :gutter=10>
        <el-col :span=4>
          <el-form-item label="库房">
            <el-select style="width: 100%;" v-model="query.drugDepositoryId" placeholder="请选择" :disabled="true" >
              <el-option
                v-for="item in depositoryEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-button type="primary" @click="add" :disabled="isCommit">添加盘点商品</el-button>
    <br>
    <br>
    <!-- 无限滑动表格 -->
    <el-table
      v-el-table-infinite-scroll="getList"
      :infinite-scroll-distance="10"
      :infinite-scroll-immediate="false"
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="50">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="仓库" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.depositoryName }}
        </template>
      </el-table-column> -->
      <el-table-column label="编码" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.drugCode }}
        </template>
      </el-table-column>
      <el-table-column label="名称" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.drugCommonName + ' / ' + scope.row.drugName }}
        </template>
      </el-table-column>
      <el-table-column label="规格" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.drugSpecs }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="剂型" width="150" align="center">
        <template slot-scope="scope">
          {{ scope.row.drugForm }}
        </template>
      </el-table-column> -->
      <el-table-column label="生产日期" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.productTime.substr(0,10) }}
        </template>
      </el-table-column>
      <el-table-column label="有效期至" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.expiration.substr(0,10) }}
        </template>
      </el-table-column>
      <el-table-column label="库存数量" width="130" align="center">
        <template slot-scope="scope">
          {{ scope.row.inventory + ' ' + scope.row.outerUnit}} {{ scope.row.subInventory===undefined || scope.row.subInventory==0 ? undefined : ', ' + scope.row.subInventory + ' ' + scope.row.innerUnit }}
        </template>
      </el-table-column>
      <el-table-column label="盘点整装数量" width="200" align="center">
        <template slot-scope="scope">
          <el-input type="Number" min=0 v-model="scope.row.checkNum" @input="inputcheckNum(scope.row)" :disabled="isCommit">
            <template slot="append">
              {{ scope.row.outerUnit }}
            </template>
          </el-input>
        </template>
      </el-table-column>
      <el-table-column label="盘点分装数量" width="200" align="center">
        <template slot-scope="scope">
          <el-input type="Number" min=0 v-model="scope.row.subCheckNum" @input="inputcheckNum(scope.row)" :disabled="isCommit || scope.row.sellMethod === 1">
            <template slot="append">
              {{ scope.row.innerUnit }}
            </template>
          </el-input>
        </template>
      </el-table-column>
      <el-table-column label="差值" width="150" align="center">
        <template slot-scope="scope">
          {{scope.row.difNum===undefined ? undefined : scope.row.difNum + ' ' + scope.row.outerUnit}} {{ scope.row.subDifNum===undefined || scope.row.subDifNum==0 ? undefined : ', ' + scope.row.subDifNum + ' ' + scope.row.innerUnit }}
        </template>
      </el-table-column>
    </el-table>

    <div class="footer">
      <el-button type="warning" v-if="form.status != 1 && form.status != 2 " :loading="commitBtnLoading" @click="confirm(0)">保存</el-button>
      <div style="width:200px;display: inline-block;"> </div>
      <el-button type="primary" v-if="form.status != 1 && form.status != 2 " :loading="commitBtnLoading" @click="confirm(1)">提交</el-button>
      <div style="width:100px;display: inline-block;"> </div>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="formVisible" :closeOnClickModal="false">
      <h2>添加</h2>
      <el-form ref="addForm" :model="addForm" label-width="120px" :rules="addFormRules">
        <el-form-item label="商品名">
          <el-autocomplete
            value-key="pinyinCode"
            class="inline-input"
            v-model="searchValue"
            :fetch-suggestions="querySearch"
            placeholder="请输入 拼音简码"
            :trigger-on-focus="false"
            @select="handleSelect"
            style="width: 100%;"
          >
          <template slot-scope="{ item }">
            <span >{{ item.name+'/' }}</span>
            <span >{{ item.commonName+' ' }}</span>
            <span >{{ item.form+' ' }}</span>
            <span >{{ item.specs+' '  }}</span>
            <span >{{ item.factory }}</span>
          </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item label="生产日期" >
          <el-date-picker v-model="addForm.productTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" ></el-date-picker>
        </el-form-item>
        <el-form-item label="保质期（月）" >
          <el-input class="drug-input" v-model="addForm.qualityTime" :disabled="addForm.productTime === undefined " @input="inputQualityTime"></el-input>
        </el-form-item>
        <el-form-item label="有效期至" >
          <el-date-picker v-model="addForm.expiration" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" :disabled="addForm.productTime === undefined" @input="inputExpirationTime" ></el-date-picker>
        </el-form-item>
        
        <el-form-item label="盘点整装数量">
          <el-input type="Number" min=0 v-model="addForm.checkNum" @input="inputFormcheckNum"></el-input>
        </el-form-item>
        <el-form-item label="盘点分装数量" v-if="form.sellMethod === 2">
          <el-input type="Number" min=0 v-model="addForm.subCheckNum" @input="inputFormcheckNum"></el-input>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addConfirm">确 定</el-button>
          <div style="width:200px;display: inline-block;"> </div>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getList as getStoreList, getChildrenDepositoryList, getAvailableDepositoryList } from '@/api/store'
import { addOrUpdate, getInfo, queryDepositoryNumList } from '@/api/checkRepository'
import { stringToDate, dateToString} from '@/utils/dateUtil'
import { getListByPinyinCode } from '@/api/drug'

export default {
  name: "CheckPage",
  filters: {
    statusColorFilter(status) {
      const statusMap = ['success', 'warning', 'primary', 'danger']
      return statusMap[status]
    },
    statusNameFilter(status) {
      const statusMap = ['草稿', '待审批', '审批完成', '已拒绝']
      return statusMap[status]
    }
  },
  data() {
    const validatePlan = (rule, value, callback) => {
      if (!value) callback(new Error('请填写计划名称')) 
      else callback()
    }
    const validateType = (rule, value, callback) => {
      if (!value) callback(new Error('请选择类型'))
      else callback()
    }
    const validateDept = (rule, value, callback) => {
      if (!this.form.depository) callback(new Error('请选择部门'))
      else callback()
    }
    return {
      list: [],
      listLoading: true,
      toUpdateBtnLoading: false,
      toInfoBtnLoading: false,
      commitBtnLoading: false,
      currentPage: 1,
      pageSize: 10,
      total: 20,
      curIndex: -1,
      infoVisible: false,
      formVisible: false,
      dialogTitle: '',
      info: {},
      form: {},
      addForm: {},
      purchaseOrderList: [],
      typeEnum: ["集中", "临时"],
      depositoryEnum: [],
      suppliers: [],
      query: {},
      tagEnum: [{id: 1, name: '热销'},{id: 2, name: '促销'}],
      dugTypeTreeList: [],
      formRules: {
        plan: [{ required: true, trigger: 'blur', validator: validatePlan }],
        type: [{ required: true, trigger: 'blur', validator: validateType }],
        dept: [{ required: true, trigger: 'blur', validator: validateDept }],
      },
      addFormRules: {},
      searchValue: '',
      isCommit: false,
    }
    
  },
  created() {
    this.fetchData()
  },
  methods: {
    /* 滑到底部 加载函数*/
    getList() {
      if( this.list.length >= this.total ) return
      
      var loginInfo = this.$store.getters.userInfo.loginInfo
      var deptId = loginInfo.loginDept.deptId
      if(this.form.id) {  // from check list
        const reqBody = {
          currentPage: ++this.currentPage,
          pageSize: this.pageSize,
          checkId: this.form.id
        }
        getInfo(reqBody).then(response=>{
          console.log(response)
          response.data.records.forEach(item=>{
            item.difNum =  item.checkNum - item.inventory
            item.subDifNum =  item.subCheckNum - item.subInventory
          })
          this.list.push(...response.data.records)
          this.total = response.data.total
          this.listLoading = false
        })
      } else { // add
        const reqBody = {
          currentPage: ++this.currentPage,
          pageSize: this.pageSize,
          drugName: this.query.drugName,
          drugDepositoryId: this.query.drugDepositoryId
        }
        queryDepositoryNumList(reqBody).then(response=>{
          console.log(response)
          this.list.push(...response.data.records)
          this.total = response.data.total
          this.listLoading = false
        })
      }
      
    },
    fetchData() {
      console.log("routers params", this.$route.params)
      this.form = this.$route.params
      this.isCommit = this.form.status == 1 || this.form.status == 2
      getAvailableDepositoryList({optType: 5}).then(deptRes=> {
        console.log("deptRes", deptRes)
        this.depositoryEnum = deptRes.data
      })
      if(this.form.id) {  // from check list
        // this.depositoryEnum = [{id: this.form.checkDepositoryId, name: this.form.checkDepositoryName}]
        this.query.drugDepositoryId = this.$route.params.checkDepositoryId
        const reqBody = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          checkId: this.form.id
        }
        getInfo(reqBody).then(response=>{
          console.log(response)
          this.list = response.data.records
          this.list.forEach(item=>{
            item.difNum =  item.checkNum - item.inventory
            item.subDifNum =  item.subCheckNum - item.subInventory
            item.depositoryName = this.form.checkDepositoryName
          })
          this.total = response.data.total
          this.listLoading = false
        })
      } else {  // add
        this.listLoading = true
        var loginInfo = this.$store.getters.userInfo.loginInfo
        var deptId = loginInfo.loginDept.deptId
        this.query.drugDepositoryId = this.$route.params.drugDepositoryId
        // this.depositoryEnum = storeListRes.data
        // this.$set(this.query, 'depositoryId', storeListRes.data.map(item => item.id)[0])
        const reqBody = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          drugName: this.query.drugName,
          drugDepositoryId: this.query.drugDepositoryId
        }
        queryDepositoryNumList(reqBody).then(response=>{
          console.log(response)
          this.list = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
      }
    },
    clickCurPage(val){
      this.currentPage = val
      this.fetchData()
    },
    cancel() {
      this.$router.push({path: '/store/check'})
    },
    search() {
      this.listLoading = true
      this.currentPage = 1
      const reqBody = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          drugDepositoryId: this.query.drugDepositoryId
      }
      queryDepositoryNumList(reqBody).then(response=>{
        console.log(response)
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    inputcheckNum(row) {
      // row.checkNum=row.checkNum.replace(/[^\d]/g,'')
      if(row.checkNum && row.inventory) {
        row.difNum = row.checkNum - row.inventory
      }
      console.log(row.subCheckNum)
      console.log(row.subInventory)
      if(row.subCheckNum && row.subInventory) {
        row.subDifNum = row.subCheckNum - row.subInventory
      }
    },
    inputFormcheckNum() {
      console.log(this.addForm)
      this.$set(this.addForm, 'difNum', this.addForm.checkNum)
      this.$set(this.addForm, 'subDifNum', this.addForm.subCheckNum)
    },
    confirm(type) {
      if(type === 1) {
        if(this.list.length != this.total) {
          this.$message.error('有未盘点药品，应盘点药品数量为：', this.total);
          return;
        }
        for (let index = 0; index < this.list.length; index++) {
          console.log(this.list[index].checkNum)
          if(!this.list[index].checkNum) {
            this.$message.error('未输入盘点数量，序号：' + index+1);
            return;
          }
        }
      }
      this.commitBtnLoading = true
      this.listLoading = true
      this.form.checkDepositoryId = this.query.drugDepositoryId
      this.form.status = type
      this.form.checkDetailAddReqDTOList = this.list
      addOrUpdate(this.form).then(res=>{
        this.$message({
          message: '添加成功',
          type: 'success'
        })
        this.commitBtnLoading = false
        this.$router.push({path: '/store/check'})
      }).catch(err=>{
        console.log(err)
      })
    },
    reset(){
      this.form = {}
    },
    add() {
      this.reset()
      this.dialogTitle = '添加'
      this.formVisible = true
    },
    querySearch(queryString, cb) {
      getListByPinyinCode(queryString, this.query.drugDepositoryId).then(drugListRes=>{
        // 调用 callback 返回建议列表的数据
        cb(drugListRes.data);
      })
    },
    handleSelect(item) {
      this.searchValue = item.name + '/' + item.commonName + ' ' + item.form + ' ' + item.specs + ' ' + item.factory
      console.log("searchValue", item)
      this.addForm.drugCode = item.code
      this.addForm.depositoryName = this.depositoryEnum[0].name
      this.addForm.drugName = item.name
      this.addForm.drugCommonName = item.commonName
      this.addForm.drugSpecs = item.specs
      this.addForm.drugForm = item.form
      this.addForm.inventory = 0
      this.addForm.subInventory = 0
      this.addForm.outerUnit = item.outerUnit
      this.addForm.innerUnit = item.innerUnit
      this.addForm.sellMethod = item.sellMethod
    },
    addConfirm() {
      this.list.push(this.addForm)
      console.log(this.list)
      this.formVisible = false
    },
    inputQualityTime() {
      var expirationTime = stringToDate(this.addForm.productTime)
      var year = expirationTime.getFullYear();
      var month = expirationTime.getMonth() + Number(this.addForm.qualityTime);
      expirationTime.setFullYear(year + Math.floor(month / 12)); // 设置年份
      expirationTime.setMonth(month % 12); // 设置月份
      this.$set(this.addForm, 'expiration', dateToString(expirationTime))
    },
    inputExpirationTime() {
      var productTime = stringToDate(this.addForm.productTime)
      var productYear = productTime.getFullYear();
      var productMonth = productTime.getMonth();
      var expirationTime = stringToDate(this.addForm.expirationTime)
      var expirationYear = expirationTime.getFullYear();
      var expirationMonth = expirationTime.getMonth();
      this.$set(this.addForm, 'qualityTime', expirationMonth - productMonth + (expirationYear - productYear)*12)
    },
  }
}

</script>

<style>
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
  .drug-input {
    width: 100%;
    display: inline-block;
    margin-right: 10px;
  }
  .drugs-item-title {
    line-height: 20px;
    text-align: center;
    background-color: #E4E7ED;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
  }
  .drugs-item {
    width: 140px;
    display: flex;
    flex-direction: column;
    margin-right: 20px;
  }
  .drug-name {
    width: 300px;
    word-wrap: break-word;
    margin-right: 20px;
    font-size: 15px;
    height: 58px;
    line-height: 58px;
  }

  .footer {
    display: flex;
    flex-direction: row;
    justify-content: center;
    margin: 50px;

  }
</style>@/api/checkRepository